package com.hzlx.batch.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;

import com.hzlx.MesBatchesMaterialDto;
import com.hzlx.MesMaterialBatchesDto;
import com.hzlx.SimpleMessageSender;
import com.hzlx.batch.mapper.BatchesMaterialMapper;
import com.hzlx.mesMaterialBatches.domain.MesMaterialBatches;
import com.hzlx.mesMaterialBatches.mapper.MesMaterialBatchesMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.hzlx.batch.domain.BatchesMaterial;
import com.hzlx.batch.service.IBatchesMaterialService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 物料批次及数量Controller
 * 
 * @author ruoyi
 * @date 2025-07-07
 */
@RestController
@RequestMapping("/inventory")
public class BatchesMaterialController extends BaseController
{
    @Autowired
    SimpleMessageSender sender;
    @Autowired
    private IBatchesMaterialService batchesMaterialService;
    @Autowired
    private BatchesMaterialMapper batchesMaterialMapper;
    @Resource
    private MesMaterialBatchesMapper mesMaterialBatchesMapper;
    /**
     * 查询物料批次及数量列表
     */
    @RequiresPermissions("material-service:batch:list")
    @GetMapping("/batch/list")
    public TableDataInfo list(BatchesMaterial batchesMaterial)
    {
        startPage();
        List<BatchesMaterial> list = batchesMaterialService.selectBatchesMaterialList(batchesMaterial);
        return getDataTable(list);
    }

    /**
     * 导出物料批次及数量列表
     */
    @RequiresPermissions("material-service:batch:export")
    @Log(title = "物料批次及数量", businessType = BusinessType.EXPORT)
    @PostMapping("/batch/export")
    public void export(HttpServletResponse response, BatchesMaterial batchesMaterial)
    {
        List<BatchesMaterial> list = batchesMaterialService.selectBatchesMaterialList(batchesMaterial);
        ExcelUtil<BatchesMaterial> util = new ExcelUtil<BatchesMaterial>(BatchesMaterial.class);
        util.exportExcel(response, list, "物料批次及数量数据");
    }

    /**
     * 获取物料批次及数量详细信息
     */
    @RequiresPermissions("material-service:batch:query")
    @GetMapping(value = "/batch/{batchId}")
    public AjaxResult getInfo(@PathVariable("batchId") Long batchId)
    {
        return success(batchesMaterialService.selectBatchesMaterialByBatchId(batchId));
    }

    /**
     * 新增物料批次及数量
     */
    @RequiresPermissions("material-service:batch:add")
    @Log(title = "物料批次及数量", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult add(@RequestBody BatchesMaterial batchesMaterial)
    {
        //1、根据materialId查总表，获取总表无聊数据
        MesMaterialBatches materialBatches =mesMaterialBatchesMapper.selectMesMaterialBatchesByMaterialId(batchesMaterial.getMaterialId());
        BigDecimal a1=materialBatches.getCurrentQuantity();//当前数量
        BigDecimal a2=materialBatches.getInitialQuantity();//初始数量
        BigDecimal a3=materialBatches.getPlanQuantity();//计划数量
        //2、将分表新增的物料数量增加到总表（update）中对应的计划/初始/实际数量中
        BigDecimal b1 =batchesMaterial.getCurrentQuantity();
        materialBatches.setInitialQuantity(a2.add(b1));
        materialBatches.setCurrentQuantity(a1.add(b1));
        materialBatches.setPlanQuantity(a3.add(b1));
        mesMaterialBatchesMapper.updateMesMaterialBatches(materialBatches);

        return toAjax(batchesMaterialService.insertBatchesMaterial(batchesMaterial));
    }

    /**
     * 修改物料批次及数量
     */
    @RequiresPermissions("material-service:batch:edit")
    @Log(title = "物料批次及数量", businessType = BusinessType.UPDATE)
    @PutMapping("/batch")
    public AjaxResult edit(@RequestBody BatchesMaterial batchesMaterial)
    {

        return toAjax(batchesMaterialService.updateBatchesMaterial(batchesMaterial));
    }
    @PutMapping("/batchDtos")
    public void editDtos(@RequestBody MesBatchesMaterialDto mesBatchesMaterialDto){

        //查询总表数量
        MesMaterialBatches materialBatches =mesMaterialBatchesMapper.selectMesMaterialBatchesByMaterialId(mesBatchesMaterialDto.getMaterialId().intValue());
        BigDecimal a1=materialBatches.getCurrentQuantity();//当前数量
        BigDecimal a2=materialBatches.getPlanQuantity();//计划数量
        //消耗物料
        BigDecimal b1 = mesBatchesMaterialDto.getCurrentQuantity();
        materialBatches.setCurrentQuantity(a1.subtract(b1));
        materialBatches.setPlanQuantity(a2.subtract(b1));
        //总表的消耗
        mesMaterialBatchesMapper.updateMesMaterialBatches(materialBatches);
        System.out.println("总表的消耗");
        //分表的消耗
        batchesMaterialService.updateBatchesMaterialDto(mesBatchesMaterialDto);
        System.out.println("分表的消耗");
        sender.sendUserMessage("消耗的物料：物料ID："+materialBatches.getMaterialId()+"数量："+b1);
    }




    @PutMapping("/batchDtosByOperation")
    public AjaxResult editDtosByOperation(@RequestBody MesBatchesMaterialDto mesBatchesMaterialDto) {
        try {
            //查询总表数量
            MesMaterialBatches materialBatches = mesMaterialBatchesMapper.selectMesMaterialBatchesByMaterialId(mesBatchesMaterialDto.getMaterialId().intValue());
            BigDecimal a1 = materialBatches.getCurrentQuantity();//当前数量
            BigDecimal a2 = materialBatches.getPlanQuantity();//计划数量
            //消耗物料
            BigDecimal b1 = mesBatchesMaterialDto.getCurrentQuantity();
            materialBatches.setCurrentQuantity(a1.subtract(b1));
            materialBatches.setPlanQuantity(a2.subtract(b1));
            //总表的消耗
            mesMaterialBatchesMapper.updateMesMaterialBatches(materialBatches);
            //分表的消耗
            //查询分表
            BatchesMaterial batchesMaterial = batchesMaterialService.selectByLimitOne(Math.toIntExact(mesBatchesMaterialDto.getMaterialId()));
            batchesMaterial.setPlanQuantity(batchesMaterial.getPlanQuantity().subtract(b1));
            batchesMaterial.setCurrentQuantity(batchesMaterial.getCurrentQuantity().subtract(b1));
            batchesMaterialService.updateBatchesMaterial(batchesMaterial);
            System.out.println("分表的消耗");
            return AjaxResult.success("库存扣减成功");
        } catch (Exception e) {
            // ✅ 返回失败信息
            return AjaxResult.error("库存扣减失败：" + e.getMessage());
        }
    }
    /**
     * 删除物料批次及数量
     */
    @RequiresPermissions("material-service:batch:remove")
    @Log(title = "物料批次及数量", businessType = BusinessType.DELETE)
	@DeleteMapping("/batch/{batchIds}")
    public AjaxResult remove(@PathVariable Long[] batchIds)
    {
        return toAjax(batchesMaterialService.deleteBatchesMaterialByBatchIds(batchIds));
    }
}
